import re
from rest_framework import serializers
from .models import Area
from user.models import Address


class AreaSerializer(serializers.ModelSerializer):
    """
    行政区信息序列化器
    """

    class Meta:
        model = Area
        fields = ('id', 'name')


class AddressSerializer(serializers.ModelSerializer):
    province = serializers.StringRelatedField(label='省', read_only=True)
    city = serializers.StringRelatedField(label='市', read_only=True)
    district = serializers.StringRelatedField(label='区', read_only=True)

    city_id = serializers.IntegerField(write_only=True)
    district_id = serializers.IntegerField(write_only=True)
    province_id = serializers.IntegerField(write_only=True)

    class Meta:
        model = Address
        exclude = ('user', 'is_deleted', 'create_time', 'update_time')

    def validate(self, attrs):
        if not re.match(r'^1[3-9]\d{9}$', attrs['mobile']):
            raise serializers.ValidationError('手机号码格式错误')
        return attrs

    def create(self, validated_data):
        user = self.context['request'].user
        validated_data['user'] = user

        addres = super().create(validated_data)

        return addres
        # user = self.context['request'].user
        # content = user.addresses.count()
        # if content > 10:
        #     raise serializers.ValidationError({'messages', '地址超过上线'})
        #
        # validated_data['user'] = user
        # address = super().create(validated_data)
        # return super().create(validated_data)
